package com.kongwg.java2;

import com.kongwg.java1.Person;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 调用运行时类中指定的结构：属性、方法、构造器
 * @author kongwg
 * @create 2020-12-24 20:32
 */
public class ReflectionTest {
    /**
     * 如何操作运行时类中的指定的属性 -- 需要掌握
     */
    @Test
    public void test1() throws Exception {
        Class<Person> clazz = Person.class;
        Person person = clazz.newInstance();
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);

        name.set(person,"joey");

        Object o = name.get(person);
        System.out.println(o);
    }


    /**
     * 获取运行的某个方法
     *
     */

    @Test
    public void test() throws Exception {
        Class<Person> clazz = Person.class;

        Person person = clazz.newInstance();
        Method method = clazz.getDeclaredMethod("show", String.class);

        method.setAccessible(true);

        Object obj = method.invoke(person, "CHN");

        System.out.println(obj);

        System.out.println("*******调用静态方法*********");

        Method showDesc = clazz.getDeclaredMethod("showDesc");

        showDesc.setAccessible(true);

        Object china = showDesc.invoke("china");

        System.out.println(china);



    }


    @Test
    public void test3() throws Exception {
        // 获取指定的构造器

        Class<Person> clazz = Person.class;

        Constructor<Person> dc = clazz.getDeclaredConstructor(String.class);


        dc.setAccessible(true);
        Person person = dc.newInstance("joey");
        System.out.println(person);
    }
}
